package org.mozhu.zufang.wechat.config;

import com.google.common.base.Splitter;
import com.google.common.collect.Sets;
import lombok.extern.slf4j.Slf4j;
import org.mozhu.mboot.core.config.ApplicationConfiguration;
import org.mozhu.mboot.core.web.filter.HttpLoggingFilter;
import org.mozhu.mboot.core.web.resource.CombineWebResourceConfigurer;
import org.mozhu.zufang.wechat.wx.oauth.OAuthInterceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.util.Set;

@Configuration
@Slf4j
public class WebConfiguration implements WebMvcConfigurer {
    public static final String STATIC_RESOURCE_PATTERN = "/status.ci,/assets/**,/resource/**,/static/**,/**/*.js,/**/*.css,/**/*.jpg,/**/*.png,/**/*.gif,/**/*.ico";
    public static final Set<String> STATIC_RESOURCE_PATTERNS = Sets.newHashSet(Splitter.on(",").omitEmptyStrings().trimResults().splitToList(STATIC_RESOURCE_PATTERN));

    @Autowired
    CombineWebResourceConfigurer webResourceConfigurer;

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        log.debug("addResourceHandlers");
        String profile = ApplicationConfiguration.get().getProperty("profile");
        log.info("profile = {}", profile);
        webResourceConfigurer.addResourceHandler(registry);
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(authInterceptor());
    }

    @Bean
    public OAuthInterceptor authInterceptor() {
        return new OAuthInterceptor();
    }

    @Bean
    public HttpLoggingFilter httpLoggingFilter() {
        HttpLoggingFilter filter = new HttpLoggingFilter();
        filter.setIncludePayload(true);
        filter.setIncludeClientInfo(false);
        filter.setIncludeQueryString(true);
        filter.setBeforeMessagePrefix("");
        filter.setBeforeMessageSuffix("");
        filter.setAfterMessagePrefix("");
        filter.setAfterMessageSuffix("");
        filter.setExclusions(STATIC_RESOURCE_PATTERNS);
        filter.setMaxPayloadLength(Integer.MAX_VALUE);
        return filter;
    }
}
